<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label="导航名称">
          <el-input placeholder="请输入导航名称" v-model="listQuery.item.name" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleFilter" :loading="btnLoading">
            <el-icon><search /></el-icon>
            搜索
          </el-button>
          <el-button
            @click="handleCreate()"
            :loading="btnLoading"
            type="success"
            plain>
            <el-icon><plus /></el-icon>
            添加
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="list"
      v-loading="listLoading"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" label="序号" width="60">
        <template v-slot="scope">
          <span>{{scope.row.orderNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="导航名称" prop="name"/>
      <el-table-column label="导航链接" prop="url"/>
      <el-table-column label="更新时间" width="160" align="center">
        <template v-slot="scope">
          <span>{{parseTime(scope.row.updateTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state" width="80" align="center">
        <template v-slot="scope">
          <template v-if="scope.row.state === '1'">
            <span class="enable-label">启用</span>
          </template>
          <template v-if="scope.row.state === '0'">
            <span class="forbidden-label">禁用</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="120"  class-name="small-padding fixed-width handle-td">
        <template v-slot="scope">
          <el-link
            type="primary"
            title="编辑"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-link>
          <el-link
            type="danger"
            title="删除"
            @click="handleDelete(scope.row, scope.$index)"
          >
            删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="listQuery.page.total"
      v-model:current-page="listQuery.page.num"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </pagination>

    <el-dialog
      :title="textMap[dialogStatus]"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-width="120px"
        style='width:100%;'
      >
        <el-form-item label="导航名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入导航名称"></el-input>
        </el-form-item>

        <el-form-item label="链接URL" prop="url">
          <el-input v-model="temp.url" placeholder="请输入链接URL"></el-input>
        </el-form-item>

        <el-form-item label="序号" prop="orderNum">
          <el-input v-model="temp.orderNum" placeholder="请输入序号0->n"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="temp.state">
            <el-radio
              v-for="item in stateList"
              :key="item.value"
              :label="item.value">
              {{item.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogStatus=='create'" type="success" @click="createData" :loading="btnLoading">确定</el-button>
          <el-button v-else type="success" @click="updateData" :loading="btnLoading">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { addSave, updateSave, getList, deleteSave } from '@/api/nav'
import { ENABLED_STATE_ENUM } from '@/config'
import { positiveInteger } from '@/utils/validate'
import { parseTime } from '@/utils'
import { mapGetters } from 'vuex'
// 图标组件
import { Search, Plus } from '@element-plus/icons-vue'
// 分页组件
import Pagination from '@/components/Pagination'

export default {
  name: 'business',
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  components: {
    Pagination,
    Search,
    Plus
  },
  data() {
    // 校验正整数
    const versionNum = (rule, value, callback) => {
      value = value * 1
      if (value === 0) {
        callback()
      } else {
        if (!positiveInteger(value)) {
          callback(new Error('请输入小于11位的整数'))
        } else {
          callback()
        }
      }
    }
    return {
      btnLoading: false,
      dialogVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      temp: {
        state: '1'
      },
      rules: {
        name: [
          { required: true, message: '请输入导航名称', trigger: 'change' },
          { max: 50, message: '导航名称最大长度50位', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入链接URL', trigger: 'change' },
          { max: 255, message: '链接URL最大长度255位', trigger: 'change' }
        ],
        orderNum: [
          { required: true, message: '请填写序号', trigger: 'change' },
          { required: true, validator: versionNum, trigger: 'change' }
        ]
      },
      listLoading: false,
      list: [],
      listQuery: {
        page: {
          num: 1,
          total: 0,
          size: 10
        },
        item: {
          name: ''
        }
      },
      // 状态
      stateList: ENABLED_STATE_ENUM
    }
  },
  watch: {
    // 表单内容体
    temp: {
      handler: function(val, oldVal) {
      },
      deep: true
    },
    // 搜索条件体
    listQuery: {
      handler: function(val, oldVal) {
      },
      deep: true
    }
  },
  created() {
  },
  activated() {
    // 取列表
    this.getList()
  },
  deactivated() {
  },
  methods: {
    parseTime(time, cFormat) {
      return parseTime(time, cFormat)
    },
    // 改变每页显示条数
    handleSizeChange(val) {
      this.listQuery.page.size = val
      this.getList()
    },
    // 改变当前页面
    handleCurrentChange(val) {
      this.listQuery.page.num = val
      this.getList()
    },
    // 搜索
    handleFilter() {
      this.btnLoading = true
      this.listQuery.page.num = 1
      this.getList().then(() => {
        this.btnLoading = false
      }).catch(() => {
        this.btnLoading = false
      })
    },
    // 获取列表
    getList() {
      this.listLoading = true
      return getList(this.listQuery).then(response => {
        this.list = response.data.records
        this.listQuery.page.total = response.data.total
        this.listLoading = false
      }).catch(err => {
        err
        this.listLoading = false
      })
    },
    // 重置数据
    resetTemp() {
      this.temp = {
        state: '1'
      }
      return this.temp
    },
    // 添加
    handleCreate(row) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, this.resetTemp(), row) // copy obj
      this.dialogStatus = 'update'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加 - 保存
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          addSave(this.temp).then(response => {
            this.btnLoading = false
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(err => {
            this.btnLoading = false
            err
          })
        }
      })
    },
    // 编辑 - 保存
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          updateSave(this.temp).then(response => {
            this.btnLoading = false
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(err => {
            this.btnLoading = false
            err
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        width: 100
      }).then(() => {
        deleteSave({
          id: row.id
        }).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }).catch(err => {
          err
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
